public class HashBuck {

    static class Node{
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[]array=new Node[10];;
    public int usedSize;
    private static final double DEFAULT_LOAD_FACTOR=0.75f;

    public void push(int key,int val){
        int index=key % array.length;
        Node cur=array[index];
        while(cur!=null){
            if(cur.key==key){
                cur.val=val;
                return;
            }
            cur=cur.next;
        }
        //没有找到当前链表中存在该节点
        Node node=new Node(key,val);
        //头插法或者尾插法都行    下面实现的是头插法
        node.next=array[index];
        array[index]=node;
        usedSize++;
        if(doLoadFactor()>=DEFAULT_LOAD_FACTOR){    //判断负载因子是否大于0.75  大于则需要扩容
            resize();
        }
    }

    private void resize() {           //扩容
        Node[]newArray=new Node[2*array.length];
        for (int i = 0; i <array.length ; i++) {
            Node cur=array[i];
            while(cur!=null){
                int newIndex=cur.key % newArray.length;
                Node curN=cur.next;
                cur.next=newArray[newIndex];
                newArray[newIndex]=cur;
                cur=curN;
            }
        }
    }

    private double doLoadFactor(){        //计算负载因子
        return usedSize*1.0/array.length;
    }
    //获取节点
    public int getVal(int key){
        int index=key%array.length;
        Node cur=array[index];
        while(cur!=null){
            if(cur.key==key){
                return cur.val;
            }
            cur=cur.next;
        }
        return -1;
    }
}
